//发送请求
import ApiService from "@/core/services/api.service";
import JwtService from "@/core/services/jwt.service";
import Sweetalert from "sweetalert2";
import i18n from "@/core/plugins/vue-i18n";
//验证身份验证
export const VERIFY_AUTH = "/service";
//登录
export const LOGIN = "/Login/signIn";
//注销
export const LOGOUT = "logout";
//注册
export const REGISTER = "/Register/verifyUser";
//qq登录
export const QQLOGIN = "/QQ/oauth";
//更新用户
export const UPDATE_PASSWORD = "updateUser";
//条款
export const CLAUSE = "/clause";
//发送验证码
export const SEND_VERIFICATION_CODE = "/ForgetPassword/phoneCode";
//验证验证码
export const VERIFICATION_CODE = "/ForgetPassword/phoneCodeVerification";
//登出并清空token 用户，错误信息
export const PURGE_AUTH = "logOut";
//设置用户
export const SET_AUTH = "setUser";
//设置密码
export const SET_PASSWORD = "setPassword";
//设置错误提示信息
export const SET_ERROR = "setError";
//获取设备名
export const DEVICE_NAME = "/deviceName";
//关于
export const ABOUT = "/about";
//状态
const state = {
    //错误
    errors: null,
    //用户
    user: {},
    //已验证
    isAuthenticated: !!JwtService.getToken(JwtService.getToken("user"))
};
const getters = {
    //当前用户
    currentUser(state) {
        return state.user;
    },
    //已验证
    isAuthenticated(state) {
        return state.isAuthenticated;
    }
};
const actions = {
    //登录动作
    [LOGIN](context, credentials) {
        return new Promise((resolve, reject) => {
            ApiService.post(LOGIN, credentials).then(({data}) => {
                if (data.code !== 200) {
                    context.commit(SET_ERROR, data.message);
                    reject(data);
                } else {
                    context.commit(SET_AUTH, data);
                    resolve(data);
                }
            }).catch(({response}) => {
                reject(response);
            });
        });
    },
    [REGISTER](context, credentials) {
        return new Promise((resolve, reject) => {
            ApiService.post(REGISTER, credentials)
                .then(({data}) => {
                    if (data.code === 200) {
                        ApiService.post(LOGIN, credentials).then(({data}) => {
                            if (data.code === 200) {
                                context.commit(SET_AUTH, data);
                                resolve(data);
                            }
                        });
                    } else {
                        context.commit(SET_ERROR, data);
                        reject(data);
                    }
                }).catch(({response}) => {
                reject(response);
            });
        });
    },
    [SEND_VERIFICATION_CODE](context, credentials) {
        return new Promise((resolve, reject) => {
            //post请求
            ApiService.post(SEND_VERIFICATION_CODE, credentials).then(({data}) => {
                if (data.code !== 200) {
                    context.commit(SET_ERROR, data.message);
                    reject(data);
                } else {
                    context.commit(SET_AUTH, data);
                    resolve(data);
                }
            }).catch(e => {
                reject(e);
            });
        });
    },
    [VERIFICATION_CODE](context, credentials) {
        return new Promise((resolve, reject) => {
            //post请求
            ApiService.post(VERIFICATION_CODE, credentials).then(({data}) => {
                if (data.code !== 200) {
                    context.commit(SET_ERROR, data.message);
                    reject(data);
                } else {
                    context.commit(SET_AUTH, data);
                    resolve(data);
                }
            }).catch(e => {
                reject(e);
            });
        });
    },
    [ABOUT](context, credentials) {
        return new Promise((resolve, reject) => {
            //post请求
            ApiService.post(ABOUT, credentials).then(({data}) => {
                if (data.code !== 200) {
                    context.commit(SET_ERROR, data.message);
                    reject(data);
                } else {
                    context.commit(SET_AUTH, data);
                    resolve(data);
                }
            }).catch(e => {
                reject(e);
            });
        });
    },
    [CLAUSE](context, credentials) {
        return new Promise((resolve, reject) => {
            //post请求
            ApiService.post(CLAUSE, credentials).then(({data}) => {
                if (data.code !== 200) {
                    reject(data);
                } else {
                    resolve(data);
                }
            }).catch(e => {
                reject(e);
            });
        });
    },
    //QQ登录动作
    [QQLOGIN](context, credentials) {
        return new Promise((resolve, reject) => {
            //post请求
            ApiService.post(QQLOGIN, credentials)
                .then(({data}) => {
                    if (data.code === 500) {
                        reject(data);
                    } else {
                        resolve(data);
                    }
                })
                .catch(data => {
                    reject(data);
                });
        });
    },
    [LOGOUT](context, credentials) {
        const userNameToken = credentials;
        //删除token信息
        ApiService.removeHeader();
        if (userNameToken === undefined) {
            context.commit(PURGE_AUTH);
        } else {
            ApiService.post(LOGOUT, {userNameToken})
                .then(({data}) => {
                    if (data.code === 200) context.commit(PURGE_AUTH);
                })
                .catch(({response}) => {
                    context.commit(SET_ERROR, response.data.errors);
                });
        }
    },
    [DEVICE_NAME](context, credentials) {
        return new Promise((resolve, reject) => {
            ApiService.post(DEVICE_NAME, credentials)
                .then(({data}) => {
                    if (data.code === 200) {
                        context.commit(SET_AUTH, data);
                        resolve(data);
                    } else {
                        context.commit(SET_ERROR, data);
                        reject(data);
                    }
                });
        });
    },
    [VERIFY_AUTH](context) {
        if (JwtService.getToken("user") !== null) {
            //设置请求头信息
            ApiService.setHeader(JwtService.getToken("user"));
            const ip = "127.0.0.1";
            const port = 8081;
            const timeout = 5000;
            //发送post请求
            ApiService.post(VERIFY_AUTH, {ip, port, timeout})
                //请求成功
                .then(({data}) => {
                    if (data.code === 407) {
                        context.commit(PURGE_AUTH);
                        if (data.message === "token错误" || data.message === "会话超时请重新登录") {
                            new Swl(i18n.t('landing_page.login.session_time_out'), "error");
                        } else if (data.message === "已被重新登录") {
                            new Swl(i18n.t('landing_page.login.login_again'), "error");
                        } else {
                            if (data.message !== "欢迎登录") new Swl(data.message, "error");
                        }
                    }
                })
                .catch(() => {
                    context.commit(PURGE_AUTH);
                    //弹出框
                    new Swl(i18n.t('menu.connection_error'), "error");
                });
        } else {
            // 没有token信息直接注销
            context.commit(PURGE_AUTH);
        }
        //弹出框
        function Swl(text, icon) {
            //函数显示一个简单的Sweetalert2弹出窗口。
            Sweetalert.fire({
                text: text,
                icon: icon,
                confirmButtonColor: "rgb(163,165,169)",
                heightAuto: false
            }).then(function (isOk) {
                //判断是否点击确认
                if (isOk) window.location.reload();
            })
        }
    },
    //更新密码
    [UPDATE_PASSWORD](context, payload) {
        //发起put请求
        return ApiService.put("password", payload).then(({data}) => {
            context.commit(SET_PASSWORD, data);
            return data;
        });
    }
};
const mutations = {
    //设置错误
    [SET_ERROR](state, error) {
        state.errors = error;
    },
    //设置验证
    [SET_AUTH](state, user) {
        //已验证状态设置true
        state.isAuthenticated = true;
        //用户信息
        state.data = user;
        //错误信息设为空
        state.errors = {};
        //在localStorage中保存token
        JwtService.saveToken("userName", user.data.username);
        JwtService.saveToken("user", user.data.username + "token");
        JwtService.saveToken(user.data.username + "token", user.data.token);
    },
    //设置密码
    [SET_PASSWORD](state, password) {
        state.user.password = password;
    },
    //注销操作
    [PURGE_AUTH](state) {
        //已验证状态设置false
        state.isAuthenticated = false;
        //用户信息设为空
        state.user = {};
        //错误信息设为空
        state.errors = {};
        //在localStorage中删除token
        JwtService.destroyToken(JwtService.getToken("user"));
        JwtService.destroyToken("user");
        JwtService.destroyToken("userName");
    }
};
export default {
    state,
    actions,
    mutations,
    getters
};
